<?php
	
	include_once '../modelo/applications_model.php';
	
	class ControladorAplicaciones{
		
		public $insertString = "INSERT INTO APPLICATIONS(IMAGE_ID,USER_ID,APP_DESCRIPTION,APP_NAME,APP_VERSION,APP_DATE_CREATED,APP_DATE_UPDATED) VALUES ";
		public $query = "";
		public $appModel = null;
		
		function __construct(){
			$this->appModel = new ApplicationsModel();			
		}
		
		public function searchActiveApplication($user_id,$app_name){
			
			$query = "SELECT A.* FROM APPLICATIONS A, USERS B WHERE A.USER_ID = B.USER_ID AND B.USER_ID = ".$user_id." AND A.APP_NAME = '".$app_name."';";
			
			$select = $this->appModel->searchActiveApplication($query);						
			
				while ($row = $select)
				  return $row[0];
		}
		
		public function searchApplicationName($app_id){
			
			$query = "SELECT APP_NAME FROM APPLICATIONS WHERE APP_ID = ".$app_id;
			
			$select = $this->appModel->searchActiveApplication($query);						
			
				while ($row = $select)
				  return $row[0];
		}
		
		public function searchImageIconApp($app_id){
			
			$query = "SELECT IMAGE_FILE_NAME FROM IMAGES WHERE IMAGE_ID = (SELECT IMAGE_ID FROM APPLICATIONS WHERE APP_ID = ".$app_id.")";	
			
			$select = $this->appModel->searchActiveApplication($query);						
			
				while ($row = $select)
				  return $row[0];
		}
		
		public function searchApplicationDescription($app_id){
			$query = "SELECT APP_DESCRIPTION FROM APPLICATIONS WHERE APP_ID = ".$app_id;	
			
			$select = $this->appModel->searchActiveApplication($query);						
			
				while ($row = $select)
				  return $row[0];
		}
		
		public function searchApplicationVersion($app_id){
			$query = "SELECT APP_VERSION FROM APPLICATIONS WHERE APP_ID = ".$app_id;	
			
			$select = $this->appModel->searchActiveApplication($query);						
			
				while ($row = $select)
				  return $row[0];
		}
		
		// Método para impresión de tablas de aplicaciones
				
		public function searchUserApplications($user_id){
			
			$query = "SELECT A.* FROM APPLICATIONS A, USERS B WHERE B.USER_ID = A.USER_ID AND B.USER_ID = ".$user_id;
			$select = $this->appModel->searchUserApplications($query);			
			
				if ($select == null || pg_num_rows($select) == 0)
					return '<h1 class="title"><a href="#">Usted no tiene aplicaciones!</a>				</h1>
		    	<div class="entry"> <br /> Puede comenzar creando una facilmente en el panel de la izquierda.<br /> <br /> <img src="../imagenes/announcment.jpg" width="450" height="380" />';
				else 
					{

						$headerTable = '<table width="501" border="0"> <tr>
										  <td width="133">Nombre</td>
										  <td width="127">Creada el</td>
										  <td width="110">Actualizada el</td>
										  <td width="103" colspan="2">Opciones</td>
										</tr>';
				
						$footerTable = '</table>';
						
						$contentTable = '';
						
						while ($row = pg_fetch_row($select)) {
							
							set_time_limit(0);
							
							$contentTable = $contentTable. ' <tr>
										  <td><a href="sections_index.php?user_id='.$user_id.'&app_id='.$row[0].'">'.$row[4].'</a></td>
										  <td>'.$row[6].'</td>
										  <td>'.$row[7].'</td>
										  <td><img src="../imagenes/edit_app.png" alt="" width="75" height="30" /></td>
										  <td><img src="../imagenes/delete_app.png" alt="" width="88" height="31" onClick="deleteApplication('.$row[0].')"/></td>
										</tr>'; 	
							
						}
						
						return '<h1 class="title"><a href="#">Tus aplicaciones!</a>				</h1>
		    	<div class="entry">'.$headerTable.$contentTable.$footerTable;
					}
		}
		
		// Método para crear una aplicación
		
		function createApplication(Application $app){			
		
			$description = $app->getAppDescription();
			
				if (empty($description))
								 
				$query = $this->insertString ."(".$app->getImageId().",".$app->getUserId().",NULL,'".$app->getAppName()."','".$app->getAppVersion()."','".$app->getAppCreatedDate()."','".$app->getAppUpdatedDate()."')";
				else
				$query = $this->insertString ."(".$app->getImageId().",".$app->getUserId().",'".$app->getAppDescription()."','".$app->getAppName()."','".$app->getAppVersion()."','".$app->getAppCreatedDate()."','".$app->getAppUpdatedDate()."')"; 
			
			return $this->appModel->createApplication($query);
		}
		
		// Métodos para generar una aplicación
		
		function generarAplicacion($appId, $secId,$section_name,$folderApp){					
			
			$this->query = "SELECT A.type_element, A.order_element, A.id FROM
							(((SELECT 'TE' type_element, a.element_order order_element, a.element_id id
						FROM element_text a, sections c, applications d
						WHERE a.sec_id = c.sec_id AND d.app_id = c.app_id AND d.app_id = ".$appId." AND c.sec_id = ".$secId." ORDER BY a.element_order)
						UNION
						(SELECT 'ML' type_element, b.element_order order_element, b.element_id id
						FROM menu_list b, sections c, applications d
						WHERE b.sec_id = c.sec_id AND d.app_id = c.app_id AND d.app_id = ".$appId." AND c.sec_id = ".$secId." ORDER BY b.element_order) UNION (SELECT 'GE' type_element, b.element_order order_element, b.element_id id
						FROM gallery_element b, sections c, applications d
						WHERE b.sec_id = c.sec_id AND d.app_id = c.app_id AND d.app_id = ".$appId." AND c.sec_id = ".$secId." ORDER BY b.element_order)) ORDER BY order_element) A
						";	
						
			$select = $this->appModel->searchApplicationsSectionsAndElements($this->query);
			
			$sHTML_Content = '<section id = "'.$section_name.'">';
			$sHTML_SectionContent = '';
			$sHTML_EndContent = '</section>';
			
					while ($row = pg_fetch_row($select)) {

							set_time_limit(0);
							
								 switch($row[0]){
									 
									case TEXT_ELEMENT: 
											$sHTML_SectionContent = $sHTML_SectionContent.$this->putTextContent($row[2])."<br />"; 												
									break;
									
									case MENU_LIST: $sHTML_SectionContent = $sHTML_SectionContent.$this->putMenuElementsInList($row[2])."<br />"; 																					
									break;
									
									case GALLERY_ELEMENT: $sHTML_SectionContent = $sHTML_SectionContent.$this->putImagesOfGallery($row[2],$folderApp);
									break;  
									 
								 }
					}
			return $sHTML_Content.$sHTML_SectionContent.$sHTML_EndContent;
		}
		
		function putTextContent($idElement){
		   
		   
		   $query = "select * from element_text where element_id = ".$idElement;
		   $select = $this->appModel->searchContentTextElement($query);		   
		   
			   while ($row = $select)
					  return $row[3];
		}
		
		function putImagesOfGallery($idGallery,$folderImages){
			
			$query = "select image_file_name from images where image_id in (select image_id from image_element where gal_element_id = ".$idGallery.")";
;
			$select = $this->appModel->searchImagesOfGallery($query);
			
			$uptag = '<table align="center">';
			$downtag = "</table>";	
			$images = '';
			$i = 0;
			$arrayImages = array();
			
				while ($row = pg_fetch_row($select)) {
					$arrayImages[$i] = '<img src="../images/'.$row[0].'" class="thumb"/>';
					$i = $i + 1;
				}
			$countImages = count($arrayImages);
			$i = 0;
			
				while ($countImages != 0){
					
					if ($countImages >= 2){
						$images = $images.'<tr><th align="center">'.$arrayImages[$i].'</th><th align="center">'.$arrayImages[$i+1].'</th></tr>';
						$countImages = $countImages - 2;
						$i = $i + 2;			
					}
					else {
						$images = $images.'<tr><th align="center" colspan="2">'.$arrayImages[$i].'</th></tr>';
						$countImages = $countImages - 1;
						$i = $i + 1;			
					}
				}

			return $uptag.$images.$downtag;
		}
		
		function putMenuElementsInList($idMenuList){
			
			$query = "select * from menu_element where men_element_id = ".$idMenuList."";
			$select = $this->appModel->searchElementsOfMenuList($query);
			
			$upMenuTag = '<ul class="nav">';
			$botMenuTag = '</ul>';
			$liMenuTags = '';
			
				while ($row = pg_fetch_row($select)) {
					if (strlen($row[5]) == 0)
						$liMenuTags = $liMenuTags.'<li> <a href="#"> '.$row[4].' </a></li>';						
					else
					    $liMenuTags = $liMenuTags.'<li> <a href="'.$row[5].'.html"> '.$row[4].' </a></li>';
				}
			return $upMenuTag.$liMenuTags.$botMenuTag;
		}
		
		
		function updateApplication($app){
									
		  $query = "UPDATE APPLICATIONS SET APP_NAME = '".$app["app_name"]."', APP_DESCRIPTION = '".$app["app_description"]."', APP_VERSION = '".$app["app_version"]."' where APP_ID = " .$app["app_id"];		  		
		  return $this->appModel->updateApplication($query);
		}
	}

?>